#import "USWaveformView.h"

@interface USWaveformView ()

@property (nonatomic, strong) CADisplayLink *displayLink;
@property (nonatomic, assign) NSTimeInterval duration;
@property (nonatomic, assign) NSTimeInterval elapsed;
@property (nonatomic, assign) BOOL isPlaying;

@end

@implementation USWaveformView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        _barWidth = 2;
        _spacing = 2;
        _barColor = [UIColor systemBlueColor];
        _barCornerRadius = 1;
        _playingIndex = -1;
        self.backgroundColor = UIColor.clearColor;
    }
    return self;
}

- (void)setVolumes:(NSArray<NSNumber *> *)volumes {
    _volumes = volumes;
    [self setNeedsDisplay];
}

- (void)setPlayingIndex:(NSInteger)playingIndex {
    _playingIndex = playingIndex;
    [self setNeedsDisplay];
}

//- (void)drawRect:(CGRect)rect {
//    if (!self.volumes || self.volumes.count == 0) return;
//
//    CGContextRef ctx = UIGraphicsGetCurrentContext();
//    CGContextClearRect(ctx, rect);
//
//    CGFloat maxHeight = rect.size.height;
//    CGFloat centerY = maxHeight / 2.0;
//
//    for (NSInteger i = 0; i < self.volumes.count; i++) {
//        CGFloat x = i * (self.barWidth + self.spacing);
//        if (x + self.barWidth > rect.size.width) break;
//
//        CGFloat normalized = self.volumes[i].floatValue;
//        CGFloat barHeight = MAX(4, normalized * maxHeight);
//        CGFloat y = centerY - barHeight / 2.0;
//
//        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(x, y, self.barWidth, barHeight)
//                                                         cornerRadius:self.barCornerRadius];
//
//        UIColor *color = self.barColor;
//        if (self.isPlaying) {
//            CGFloat alpha = i <= self.playingIndex ? 1.0 : 0.3;
//            color = [self.barColor colorWithAlphaComponent:alpha];
//        }
//        [color setFill];
//        [path fill];
//    }
//    
//}

- (void)drawRect:(CGRect)rect {
    if (!self.volumes || self.volumes.count == 0) return;

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextClearRect(ctx, rect);

    CGFloat maxHeight = rect.size.height;
    CGFloat centerY = maxHeight / 2.0;

    for (NSInteger i = 0; i < self.volumes.count; i++) {
        CGFloat x = i * (self.barWidth + self.spacing);
        if (x + self.barWidth > rect.size.width) break;

        // 改进后的高度映射
        CGFloat raw = self.volumes[i].floatValue; // 0 ~ 1
        CGFloat normalized = powf(raw, 0.35); // 非线性映射，更有层次感
        CGFloat barHeight = MAX(6, normalized * maxHeight); // 保证至少 8pt 高
        CGFloat y = centerY - barHeight / 2.0;

        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(x, y, self.barWidth, barHeight)
                                                         cornerRadius:self.barCornerRadius];

        UIColor *color = self.barColor;
        if (self.isPlaying) {
            CGFloat alpha = i <= self.playingIndex ? 1.0 : 0.25;
            color = [self.barColor colorWithAlphaComponent:alpha];
        }

        [color setFill];
        [path fill];
    }
}

- (void)startPlayingAnimationWithDuration:(NSTimeInterval)duration {
    self.elapsed = 0;
    self.duration = duration;
    self.playingIndex = -1;
    [self stopPlayingAnimation];
    self.isPlaying = YES;
    self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(updatePlayingFrame)];
    [self.displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
}

- (void)stopPlayingAnimation {
    [self.displayLink invalidate];
    self.displayLink = nil;
    self.playingIndex = -1;
    self.isPlaying = NO;
    [self setNeedsDisplay]; // 恢复为不透明
}

- (void)updatePlayingFrame {
    if (!self.volumes || self.volumes.count == 0) return;

    self.elapsed += self.displayLink.duration;

    NSInteger totalFrames = self.volumes.count;
    NSInteger current = MIN(totalFrames - 1, self.elapsed / self.duration * totalFrames);

    self.playingIndex = current;

    if (current >= totalFrames - 1) {
        [self stopPlayingAnimation];
    }
}

@end
